<?php

class ShareController extends CloudControllerBase
{
    public function projectAction()
    {
        $user = $this->getMonitorLoginUser();
        
        $this->checkRequestParams(array(
            array(
                "key" => "id",
                "type" => "presence",
                "message" => "项目编号不能为空"),
        ));

        $localId = $this->getPost("id", '', 'striptags');

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "get userId:" . $user->userId . ", id:" . $localId . "\r\n", FILE_APPEND);

        $sql = "select id, local_id, project_name, created_at, updated_at, version, center_position_lng, center_position_lat, map_scale, user_id from project where user_id = " . $user->userId . " and local_id = '$localId' and is_removed = false order by version desc limit 1";
        $project = $this->fetchOne($sql);

        if (empty($project)) {
            $this->returnError("项目id:$localId 不存在。");
        }
        $projectId = $project["id"];
        $sql = "select id, local_id, project_id, created_at, updated_at, survey_area_name, block_type, survey_area_coordinate_points, home_lng, home_lat, work_area, work_time from survey_block where project_id = $projectId";
        $blocks = $this->fetchAll($sql);

        $sql = "select id, '{$project["local_id"]}' as project_id, lng, lat, name, elevation from project_point where project_id = $projectId";
        $points = $this->fetchAll($sql);

        $project["points"] = $points;

        foreach ($blocks as &$block) {
            $blockId = $block["id"];
            $sql = "select * from flight_task where survey_block_id = $blockId";
            $tasks = $this->fetchAll($sql);

            foreach ($tasks as &$task) {
                $task["id"] = $task["flight_task_guid"];
                $task["survey_block_id"] = $block["local_id"];
                unset($task["local_id"]);
            }

            $block["tasks"] = $tasks;
            $block["id"] = $block["local_id"];
            $block["project_id"] = $project["local_id"];
            unset($block["local_id"]);

        }
        $project["blocks"] = $blocks;
        $project["id"] = $project["local_id"];
        unset($project["local_id"]);

        $this->returnJson($project);

    }

    // 查询我的分享接口    列出全部分享的项目和被分享的项目，按照时间倒序排序
    public function listAction(){
        
        $user = $this->getMonitorLoginUser();
        
        $userId = $user->userId;
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n".date("H:i:s", time()).':'.__METHOD__.':'."listAction userId:$userId \r\n", FILE_APPEND);
        
        $sql = "select project_share.*, user.nickname, user.phone, project.project_name from project_share left join user on project_share.share_to_user_id = user.id left join project on project_share.project_id = project.id where share_from_user_id = $userId order by project_share.status asc, project_share.created_at desc";
        $sendRecords = $this->fetchAll($sql);
        
        foreach($sendRecords as &$record){
            // 查询通信消息
            $sql = "select user.id as user_id, user.nickname, project_share_message.info, project_share_message.created_at from project_share_message left join user on project_share_message.user_id = user.id where project_share_id = {$record["id"]} order by project_share_message.created_at";
            $messages = $this->fetchAll($sql);
            $record["messages"] = $messages;
            unset($record["project_id"]);
            if(empty($record["updated_at"])){
                $record["updated_at"] = $record["created_at"];
            }
            unset($record["created_at"]);
        }
        
        $sql = "select project_share.*, user.nickname, user.phone, 0 as save_as, project.project_name, project.local_id from project_share left join user on project_share.share_from_user_id = user.id left join project on project_share.project_id = project.id where share_to_user_id = $userId order by project_share.status asc, project_share.created_at desc";
        $retrieveRecords = $this->fetchAll($sql);
        
        foreach($retrieveRecords as &$record){
            if($record["status"] == 0){
                
                // 检查项目是否存在，如果存在，则需要显示另存为接口
                $sql = "select id from project where  user_id = $userId and local_id = '{$record["local_id"]}' and is_removed=0";
                $local_id = $this->fetchColumn($sql);
                
                if(!empty($local_id)){
                    $record["save_as"] = 1;
                }
            }
            
            // 查询通信消息
            $sql = "select user.id as user_id, user.nickname, project_share_message.info, project_share_message.created_at from project_share_message left join user on project_share_message.user_id = user.id where project_share_id = {$record["id"]} order by project_share_message.created_at";
            $messages = $this->fetchAll($sql);
            $record["messages"] = $messages;
            
            unset($record["project_id"]);
            if(empty($record["updated_at"])){
                $record["updated_at"] = $record["created_at"];
            }
            unset($record["created_at"]);
        }
        
        $json = array();
        $json["send"] = $sendRecords;
        $json["retrieve"] = $retrieveRecords;
        $this->returnJson($json);
    }
    
    public function shareAction(){
        // 数据有效性验证
        $user = $this->getMonitorLoginUser();
        
        $this->checkRequestParams(array(
            array(
                "key" => "phone",
                "type" => "presence",
                "message" => "手机号不能为空"
            )
        ));
        $nickname = $user->name;
        $userId = $user->userId;
        $localId = $this->getPost("local_id");
        $message = $this->getPost("message");
        
        $phones = explode(',', $this->getPost("phone"));
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n".date("H:i:s", time()).':'.__METHOD__.':'."shareAction token:".$token.", id:$localId, phone:".$this->getPost("phone").", message:$message \r\n", FILE_APPEND);
        
        $shareCount = 0;
        foreach($phones as $phone){
//             if($phone == $user->phone){
//                 $this->returnError("不能分享给自己。");
//             }
            $sql = "select * from user where phone = '$phone'";
            $toUser = $this->fetchOne($sql);
            if(empty($toUser)){
                $this->returnError("该手机号码没有注册:$phone");
            }
            $toUserId = $toUser["id"];
            
            $sql = "select * from project where local_id = '$localId' and user_id = $userId order by version desc limit 1";
            $record = $this->fetchOne($sql);
            if(empty($record)){
                $this->returnError("project id不存在。");
            }
            $this->begin();
            try{
                $projectId = $record["id"];
                $id = $this->insert ( 'project_share', array (
                        'share_from_user_id' => $userId,
                        'share_to_user_id' => $toUserId,
                        'status' => 0,
                        'project_id' => $projectId
                ) );
                $sql = "insert into project_share(share_from_user_id, share_to_user_id, status, project_id) values($userId, $toUserId, 0, $projectId)";
                file_put_contents("./log_" . date("Y-m-d") . ".txt", date("H:i:s", time()).':'.__METHOD__.':'."insert project_share: $sql.\r\n", FILE_APPEND);
//                 $this->execute($sql);
//                 $id = $this->lastInsertId();
                
                if(!empty($message)){
                    $id = $this->insert ( 'project_share_message', array (
                            'project_share_id' => $id,
                            'type' => 1,
                            'user_id' => $userId,
                            'info' => $message
                    ) );
                    $sql = "insert into project_share_message(project_share_id, type, user_id, info) values($id, 1, $userId, '$message')";
                    file_put_contents("./log_" . date("Y-m-d") . ".txt", date("H:i:s", time()).':'.__METHOD__.':'."insert project_share_message: $sql.\r\n", FILE_APPEND);
//                     $this->execute($sql);
                }
                $this->commit();
                $shareCount++;
                
                //设置分享的推送消息
                if(empty($message)){
                    $message = "'$nickname'分享给你了一个项目。";
                }
                else{
                    $message = "'$nickname'分享给你了一个项目，并留言：$message";
                }
                
                if(empty($nickname))
                    $nickname = $toUser['nickname'];
                    
                    $sql = "select id from project_share_to where share_from_user_id = $userId and share_to_user_id=$toUserId";
                
                if ($shareInfo = $this->fetchOne($sql)){
                    $id = $this->update( 'project_share_to', array (
                            'share_from_user_id' => $userId,
                            'share_to_user_id' => $toUserId,
                            'nickname' => $nickname,
                            'info' => $message),
                            "id = " . $shareInfo['id']);
//                     $sql = "update project_share_to set share_from_user_id = $userId, share_to_user_id=$toUserId ,nickname='$nickname',info='$message' where id={$shareInfo['id']} ;";
//                     file_put_contents("./log_" . date("Y-m-d") . ".txt", date("H:i:s", time()).':'.__METHOD__.':'."update project_share_to: $sql.\r\n", FILE_APPEND);
                }else{
                    $id = $this->insert ( 'project_share_to', array (
                            'share_from_user_id' => $userId,
                            'share_to_user_id' => $toUserId,
                            'nickname' => $nickname,
                            'info' => $message) );
//                     $sql = "insert into project_share_to(share_from_user_id,share_to_user_id,nickname,info)
//                     value ($userId,$toUserId,'$nickname','$info')";
//                     file_put_contents("./log_" . date("Y-m-d") . ".txt", date("H:i:s", time()).':'.__METHOD__.':'."insert project_share_to: $sql.\r\n", FILE_APPEND);
                }
                    
                $this->web_push(array(
                        'action' => 'web_share',
                        'status' => '2',
                        'data' => array(
                                'share_id' => $id,
                        ),
                        'message' => $message,
                        'token' => $this->guid()
                ), $toUserId, $user->userId );
                
                $this->tcp_push ( array (
                        'action' => 'project_share',
                        'status' => '2',
                        'data' => array(
                                'share_id' => $id,
                        ),
                        'message' => $message,
                ), $toUserId, $user->userId );
            }
            catch(Exception $e){
                $this->rollback();
                $this->returnError("分享失败：$e");
            }
        }
        
        $this->returnInfo("分享成功！{$shareCount}条。");
    }

    // 接受接口
    public function acceptAction(){
        $user = $this->getMonitorLoginUser();
        $id = $this->getPost("id");
        $phone = $user->phone;
        $message = $this->getPost("message");
        $type = $this->getPost("type");
        $name = $this->getPost("name");
        
        
        file_put_contents("./log_" . date("Y-m-d") . ".txt",  "\n".date("H:i:s", time()).':'.__METHOD__.':'."acceptAction type:$type, name:$name, phone:".$phone.", id:$id, message:$message\r\n", FILE_APPEND);
        
        $sql = "select * from project_share where id = $id";
        $share = $this->fetchOne($sql);
        
        if(empty($share)){
            $this->returnError("分享id:$id 不存在。");
        }
        
        if($share["status"] != 0){
            $this->returnError("该项目不是可以接受的状态。");
        }
        
        $sql = "select project.*, user.nickname, user.id as from_user_id from project  left join user on project.user_id = user.id where project.id = {$share["project_id"]} and is_removed = 0";
        $project = $this->fetchOne($sql);
        
        if(empty($project)){
            $this->returnError("项目id:$id 不存在。");
        }
        $fromUserId = $project["from_user_id"];
        
        $projectName = $project["project_name"]." from ".$project["nickname"];
        
        if($type == 0){
            $sql = "select * from project where user_id = {$user->userId} and local_id = '{$project["local_id"]}'";
            $temp = $this->fetchOne($sql);
            $version = 1;
            if(!empty($temp)){
                $this->returnError("项目已经存在了。");
            }
        }
        else if($type == 1){
            $sql = "select * from project where user_id = {$user->userId} and local_id = '{$project["local_id"]}' order by version desc limit 1";
            $temp = $this->fetchOne($sql);
            $version = 1;
            if(!empty($temp)){
                $version = $temp["version"] + 1;
            }
        }
        else if ($type == 2){
            $version = 1;
            $project["local_id"] = $this->guid();
            if(!empty($name)){
                $projectName = $name;
            }
        }
        else{
            $this->returnError("操作类型错误。");
        }
        
        $this->begin();
        try{
            $project["version"] = $version;
            $project["project_name"] = $projectName;
            //             $project["local_id"] = $this->guid();
            $project["user_id"] = $user->userId;
            $project["share_from_id"] =$share["share_from_user_id"];
            $oldProjectId = $project["id"];
            unset($project["id"]);
            unset($project["created_at"]);
            
            $projectId = $this->insert("project", $project);
            
            if(!empty($message)){
                $this->insert("project_share_message", array(
                        "project_share_id" => $share["id"],
                        "user_id" => $user->userId,
                        "type" => 2,
                        "info" => $message,
                ));
            }
            
            $sql = "select * from project_point where project_id = $oldProjectId";
            $points = $this->fetchAll($sql);
            
            foreach($points as $point){
                $point["project_id"] = $projectId;
                
                unset($point["id"]);
                unset($point["created_at"]);
                $this->insert("project_point", $point);
            }
            file_put_contents("./log_" . date("Y-m-d") . ".txt",  date("H:i:s", time()).':'.__METHOD__.':'."acceptAction project:".$projectId.", point:".count($points)." \r\n", FILE_APPEND);
            
            $sql = "select * from survey_block where project_id = $oldProjectId";
            $blocks = $this->fetchAll($sql);
            
            foreach($blocks as $block){
                $block["project_id"] = $projectId;
                $oldBlockId = $block["id"];
                unset($block["id"]);
                unset($block["created_at"]);
                $blockId = $this->insert("survey_block", $block);
                
                $sql = "select * from flight_task where survey_block_id = $oldBlockId";
                $tasks = $this->fetchAll($sql);
                
                foreach($tasks as &$task){
                    $task["survey_block_id"] = $blockId;
                    
                    unset($task["id"]);
                    unset($task["created_at"]);
                    $this->insert("flight_task", $task);
                }
            }
            
            $sql = "update project_share set status = 2, updated_at = now() where id = $id";
            $this->execute($sql);
            $this->commit();
        }
        catch(Exception $e){
            $this->rollback();
            $this->returnError("分享失败：$e");
        }
        
        $this->web_push(array(
                'action' => 'web_share_access',
                'status' => '2',
                'data' => array(
                        'share_id' => $id,
                ),
                'message' => "'{$user->name}'已接受了您的分享。",
                'token' => $this->guid()
                ), $fromUserId, $user->userId );
        
        $this->tcp_push ( array (
                'action' => 'project_share_access',
                'status' => '2',
                'data' => array(
                        'share_id' => $id,
                ),
                'message' => "'{$user->name}'已接受了您的分享。"
                ), $fromUserId, $user->userId );
        
        $this->returnSuccess("插入成功。");
    }

    // 拒绝接口
    public function denyAction(){
        $user = $this->getMonitorLoginUser();
        $id = $this->getPost("id");
        $message = $this->getPost("message");
        
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n".date("H:i:s", time()).':'.__METHOD__.':'."denyAction id:$id, message:$message \r\n", FILE_APPEND);
        
        $sql = "select * from project_share where id = $id and share_to_user_id = " . $user->userId;
        $record = $this->fetchOne($sql);
        if(empty($record)){
            $this->returnError("id不存在。");
        }
        
        $fromUserId = $record["share_from_user_id"];
        
        $fromUser = $this->fetchOne("select * from user where id = $fromUserId");
        
        if($record["status"] != 0){
            $this->returnError("该项目不是可以拒绝的状态");
        }
        
        $sql = "update project_share set status = 3, updated_at = now() where id = $id";
        $this->execute($sql);
        
        if(!empty($message)){
            $id = $this->insert ( 'project_share_message', array (
                'project_share_id' => $id,
                'user_id' => $user->userId,
                'type' => 3,
                'info' => $message) );
        }
        
        $this->web_push(array(
            'action' => 'web_share_deny',
            'status' => '2',
            'data' => array(
                'share_id' => $id,
            ),
            'message' => "'{$user->name}'已拒绝您的分享。",
            'token' => $this->guid()
            ), $record["share_from_user_id"], $user->userId );
        
        $this->tcp_push ( array (
            'action' => 'project_share_deny',
            'status' => '2',
            'data' => array(
                'share_id' => $id,
            ),
            'message' => "'{$user->name}'已拒绝您的分享。"
            ), $record["share_from_user_id"], $user->userId );
        
        $this->returnSuccess("已拒绝来自用户{$fromUser["niciname"]}的分享。");
    }

    // 回复指派列表接口
    public function replyAction(){
        $user = $this->getMonitorLoginUser();
        $id = $this->getPost("id");
        $message = $this->getPost("message");
        
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n".date("H:i:s", time()).':'.__METHOD__.':'."replyAction id:$id, message:$message \r\n", FILE_APPEND);
        
        $sql = "select * from project_share where id = $id";
        $record = $this->fetchOne($sql);
        if(empty($record)){
            $this->returnError("分享id不存在。");
        }
        
        $id = $this->insert ( 'project_share_message', array (
                'project_share_id' => $id,
                'user_id' => $user->userId,
                'type' => 0,
                'info' => $message) );
        
        $toUserId = 0;
        if($record["share_from_user_id"] == $user->userId){
            $toUserId = $record["share_to_user_id"];
        }
        else{
            $toUserId = $record["share_from_user_id"];
        }
        
        $this->web_push(array(
                'action' => 'web_share_message',
                'status' => '2',
                'data' => array(
                        'share_id' => $id,
                ),
                'message' => $message,
                'token' => $this->guid()
                ), $toUserId, $user->userId );
        
        $this->tcp_push ( array (
                'action' => 'project_share_message',
                'status' => '2',
                'data' => array(
                        'share_id' => $id,
                ),
                'message' => $message
                ), $toUserId, $user->userId );
        
        $this->returnSuccess("回复成功。");
    }

}